﻿namespace FSpec.Runner

open FSpec

open Gallio.Framework.Assertions 
open Gallio.Framework 
open Gallio.Model.Commands
open Gallio.Model

open System.Diagnostics 
open System
open System.Reflection 

[<AutoOpen>]
module ExecutorHelper =
    let testPassed =    
        { Time = new TimeSpan(); Status = TestStatus.Passed; ExceptionData = null }

    let testFailed = 
        { Time = new TimeSpan(); Status = TestStatus.Failed; ExceptionData = null }

    let testInconclusive =
        { Time = new TimeSpan(); Status = TestStatus.Inconclusive; ExceptionData = null }

type SpecExecutor(testContext) =
    member this.Run (methodInfo:System.Reflection.MethodInfo) =
        
        let sw = new Stopwatch()
        try
            sw.Start()
            methodInfo.Invoke(null, null) |> ignore
            sw.Stop()
            { testPassed with 
                Time = sw.Elapsed }
        with
        | :? TargetInvocationException as e ->
            sw.Stop()
            match e.InnerException with
            | :? TestInconclusiveException as i ->
                { testInconclusive with 
                    Time = sw.Elapsed; 
                    ExceptionData = i; }
            | _ as e -> 
                { testFailed with 
                    Time = sw.Elapsed; 
                    ExceptionData = e; }
        | _ as e -> 
            sw.Stop()
            raise(e)
        
       
            




